package com.example.seh.person.buy.bought;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.seh.R;
import com.example.seh.add.errands.AddErrandsActivity;
import com.example.seh.chat.ChatActivity;
import com.example.seh.constant.Constant;
import com.example.seh.person.sell.second.OrderDTO;
import com.example.seh.person.sell.second.SellAdapter;
import com.example.seh.util.BackUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyBoughtAdapter extends BaseAdapter {
    private Context context;
    private int item;
    private List<OrderDTO> lists = new ArrayList<>();
    private String[] pics;

    public MyBoughtAdapter(Context context, int item, List<OrderDTO> lists) {
        this.context = context;
        this.item = item;
        this.lists = lists;
    }

    @Override
    public int getCount() {
        if (lists != null) {
            return lists.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (lists != null) {
            return lists.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(item, null);
            viewHolder = new ViewHolder();
            viewHolder.imageView = convertView.findViewById(R.id.bought_pic);
            viewHolder.title = convertView.findViewById(R.id.bought_title);
            viewHolder.price = convertView.findViewById(R.id.sell_price);
            viewHolder.callSeller = convertView.findViewById(R.id.callSeller);
            viewHolder.sellerAddress = convertView.findViewById(R.id.seller_address);
            viewHolder.sellState = convertView.findViewById(R.id.sell_state);
            viewHolder.confirm = convertView.findViewById(R.id.confirm_buy);

            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.title.setText(lists.get(position).getGoodsDTO().getGoodsName());
        viewHolder.price.setText(lists.get(position).getGoodsDTO().getGoodsPrice()+"");
        viewHolder.sellerAddress.setText(lists.get(position).getReceiveAddress());

        if (lists.get(position).getOrderStatus() == 1){
            viewHolder.sellState.setText("交易中");
        }else if (lists.get(position).getOrderStatus() == 2){
            viewHolder.sellState.setText("交易完成");
        }

        // 设置 confirm 视图的可见性
        if (lists.get(position).getOrderStatus() == 2) {
            viewHolder.confirm.setVisibility(View.GONE);
        } else {
            viewHolder.confirm.setVisibility(View.VISIBLE);
        }

        if (lists.get(position).getGoodsDTO().getGoodsPic() != null){
            pics = lists.get(position).getGoodsDTO().getGoodsPic().split(";");
            if (!pics[0].isEmpty()) {

                Glide.with(context)
                        .load(pics[0])
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .dontAnimate()
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                if (target instanceof ImageView) {
                                    ((ImageView) target).setTag(pics[0]);  // 绑定加载请求与视图
                                }
                                return false;
                            }
                        })
                        .into(viewHolder.imageView);
            } else {
                Glide.with(context)
                        .clear(viewHolder.imageView);  // 清除之前的加载请求，避免复用时显示错误的图片
                viewHolder.imageView.setImageResource(R.drawable.wtp);  // 或者设置默认占位图像
            }
        }else {
            viewHolder.imageView.setImageResource(R.drawable.wtp);
        }

        viewHolder.callSeller.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int buyerId = lists.get(position).getUserId();
                Log.e("bought",lists.get(position).getGoodsDTO().toString());
                Intent intent = new Intent(context, ChatActivity.class);
                intent.putExtra("buniess", lists.get(position).getGoodsDTO());
                context.startActivity(intent);
            }
        });

        viewHolder.confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(parent.getContext());
                dialog.setTitle("提示")
                        .setMessage("确定收到货了吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                viewHolder.sellState.setText("交易完成");
                                //发送后台修改代取状态
                                sendState(lists.get(position).getOrderId(),viewHolder.confirm);

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                dialog.create().show();
            }
        });

        return convertView;
    }

    private void sendState(Integer OrderId,TextView confirm) {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder()
                .url(Constant.CONFIRM_BOUGHT+OrderId)
                .get()
                .build();
        Log.e("url",request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "发送数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    Log.e("okhttp", "发送成功");
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            confirm.setVisibility(View.GONE);
                        }
                    });

                } finally {
                    // 关闭响应体
                    if (response != null && response.body() != null) {
                        response.body().close();
                    }
                }


            }
        });

    }

    class ViewHolder{
        ImageView imageView;
        TextView title,price,sellState,sellerAddress,callSeller,confirm;
    }

}
